﻿using System;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using clipboardSave;
using Clipboard = System.Windows.Clipboard;
using MessageBox = System.Windows.MessageBox;

namespace clipSa
{
    public static class MySettings
    {
        internal static Properties.Settings Sets = clipSa.Properties.Settings.Default;
        internal static string[] Extensions = {".bmp", ".jpeg", ".png"};

    }
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private NotifyIcon _ni;
        private readonly ContextMenu _cm1 = new ContextMenu();
        private readonly MenuItem _menuItem1;
        private readonly MenuItem _menuItem2;
        private readonly MenuItem _menuItem3;
        public MainWindow()
        {
            _menuItem3 = new MenuItem("&Close");
            _menuItem2 = new MenuItem("&Settings");
            _menuItem1 = new MenuItem("&Expand");
            InitializeComponent();
            _cm1.MenuItems.Add(_menuItem1);
            _cm1.MenuItems.Add(_menuItem2);
            _cm1.MenuItems.Add(_menuItem3);
            MinimiseToTray(null, null);

        }

       
        /// <summary>
        /// Click on Save button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>


        private void SaveButtonClick(object sender, MouseButtonEventArgs e)
        {
           
            if (Clipboard.ContainsImage())
            {
                //var a = Enum.GetName(typeof (PixelFormat), MySettings.Sets.depth.ToString());
                Bitmap org = new Bitmap(System.Windows.Forms.Clipboard.GetImage());

                Bitmap picture = new Bitmap(org.Width, org.Height, MySettings.Sets.depth);
                try
                {
                    
                    picture.SetResolution(org.HorizontalResolution, org.VerticalResolution);
                    Graphics g = Graphics.FromImage(picture);
                    g.DrawImage(org, 0, 0);
                }
                catch (Exception exception)
                {
                    MessageBox.Show("Error converting picture: {0}. Try to change settings. Current format not supported.", exception.ToString());
                    return;
                }

                //g.Dispose();

                if (! MySettings.Sets.isAutoSave)
                {
                    SaveWithDialog(picture);
                }
                else
                {
                    if (!AutoSaveImage(picture)) MessageBox.Show("Saving file unsuccesfull!"); ;
                }
            }
            else MessageBox.Show("There is No image in the buffer");
        }

        private bool AutoSaveImage(Bitmap picture)
        {
            string fileName=null;
            if (!Directory.Exists(MySettings.Sets.defCatalog))
            {
                MessageBox.Show("Change settings! Default catalog not excist.");
                return false;
            }
            try
            {
                for(int nn =MySettings.Sets.minNN ;nn <=MySettings.Sets.maxNN ;nn++)
                {
                    fileName = MySettings.Sets.prefixFileName +nn + MySettings.Sets.sufixFileName + MySettings.Extensions[MySettings.Sets.defExt-1];
                    var file = new FileInfo(MySettings.Sets.defCatalog + "\\" + fileName);
                    if (file.Exists) continue;
                    break;
                }
                if (fileName==null)
                {
                    MessageBox.Show("Free name with current settings not available.");
                    return false;
                }
                var fs = new FileStream(MySettings.Sets.defCatalog+"\\"+fileName,FileMode.CreateNew);
                // Saves the Image in the ImageFormat
                switch (MySettings.Sets.defExt)
                {
                    case 1:
                        picture.Save(fs, ImageFormat.Bmp);
                        break;
                    case 2:
                        picture.Save(fs, ImageFormat.Jpeg);
                        break;
                    case 3:
                        picture.Save(fs, ImageFormat.Png);
                        break;
                }
                fs.Close();

            }
            catch (Exception e)
            {
                MessageBox.Show("Error: {0}", e.ToString());
                return false;
            }
            return true;
        }


        /// <summary>
        /// SaveFileDialog for Saving image from Clipboard
        /// </summary>
        /// <param name="picture"></param>
        static void SaveWithDialog(Image picture)
        {
            if (picture == null) throw new ArgumentNullException("picture");


            var saveFd = new SaveFileDialog
            {
                Filter =
                    Properties.Resources.types_of_images,
                FilterIndex = MySettings.Sets.defExt,
                Title = Properties.Resources.Save_an_Image_File
            };
            saveFd.ShowDialog();
            // If the file name is not an empty string open it for saving.
            if (saveFd.FileName != "")
            {
                // Saves the Image via a FileStream created by the OpenFile method.
                var fs = (FileStream)saveFd.OpenFile();
                // Saves the Image in the ImageFormat
                switch (saveFd.FilterIndex)
                {
                    case 1:
                        picture.Save(fs, ImageFormat.Bmp);
                        break;
                    case 2:
                        picture.Save(fs, ImageFormat.Jpeg);
                        break;
                    case 3:
                        picture.Save(fs, ImageFormat.Png);
                        break;
                }
                fs.Close();
                MySettings.Sets.defExt = saveFd.FilterIndex;
                MySettings.Sets.Save();
            }
        }

        private void ExitFromThere(object sender, EventArgs e)
        {
            Close();
        }

        private void MinimiseToTray(object sender, RoutedEventArgs e)
        {
            _ni = new NotifyIcon { Icon = Properties.Resources.arrow_down, Visible = true };
           
            ShowInTaskbar = false;
            _ni.ContextMenu = _cm1;
            Hide();
            _ni.DoubleClick += new EventHandler(NiDoubleClick);
            _ni.ContextMenu.MenuItems[0].Click += NiDoubleClick;
            _ni.ContextMenu.MenuItems[1].Click += OpenSetingsWindow;
            _ni.ContextMenu.MenuItems[2].Click += new EventHandler(ExitFromThere);


        }

        void NiDoubleClick(object sender, EventArgs e)
        {
            if (sender == null) throw new ArgumentNullException("sender");
            Show();
            ShowInTaskbar = true;
            _ni.Dispose();
        }

        private void OpenSetingsWindow(object sender, EventArgs e)
        {
            var setWin = new Window1();
            setWin.ShowDialog();
            setWin.Activate();
        }

        private void MoveWindow(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }
 
        private ImageCodecInfo GetEncoder(ImageFormat format)
        {

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }

    }
}
